<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import type { Product } from '@/types/product'
import { productService } from '@/services/apiService'
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElCard, ElMessage, ElIcon } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import LoadingSpinner from '@/components/LoadingSpinner.vue'

const router = useRouter()
const fileInput = ref<HTMLInputElement | null>(null)

// 表单数据
const productForm = ref<Partial<Product> & { images?: File[] }>({
  title: '',
  description: '',
  price: '',
  status: 1
})

const imagePreviewUrls = ref<string[]>([])
const loading = ref(false)
const errors = ref<Record<string, string>>({})

// 触发文件选择
const triggerUpload = () => {
  if (fileInput.value) {
    fileInput.value.click()
  }
}

// 处理文件选择
const handleFileSelect = (event: Event) => {
  const input = event.target as HTMLInputElement
  if (input.files && input.files.length > 0) {
    // 检查总图片数量是否超过限制
    if (imagePreviewUrls.value.length + input.files.length > 5) {
      ElMessage.error('最多只能上传5张图片!')
      return
    }
    
    // 处理每个选中的文件
    Array.from(input.files).forEach(file => {
      // 检查文件类型和大小
      if (beforeUpload(file)) {
        // 创建预览URL
        const url = URL.createObjectURL(file)
        imagePreviewUrls.value.push(url)
        
        // 添加到表单数据
        if (!productForm.value.images) {
          productForm.value.images = []
        }
        productForm.value.images.push(file)
        
        // 清除图片错误
        if (errors.value.images) {
          delete errors.value.images
        }
      }
    })
    
    // 清空input元素，以便下次选择相同的文件也能触发change事件
    input.value = ''
  }
}

// 验证表单
const validateForm = (): boolean => {
  errors.value = {}
  let isValid = true

  if (!productForm.value.title?.trim()) {
    errors.value.title = '请输入商品名称'
    isValid = false
  }

  if (!productForm.value.description?.trim()) {
    errors.value.description = '请输入商品描述'
    isValid = false
  }

  if (!productForm.value.price || parseFloat(productForm.value.price) <= 0) {
    errors.value.price = '请输入有效价格'
    isValid = false
  }

  if (!productForm.value.images || productForm.value.images.length === 0) {
    errors.value.images = '请至少上传一张图片'
    isValid = false
  } else if (productForm.value.images.length > 5) {
    errors.value.images = '最多只能上传5张图片'
    isValid = false
  }

  return isValid
}

// 移除图片
const removeImage = (index: number) => {
  // 从预览URL数组中移除
  const removedUrl = imagePreviewUrls.value.splice(index, 1)[0]
  
  // 释放Blob URL内存
  if (removedUrl && removedUrl.startsWith('blob:')) {
    URL.revokeObjectURL(removedUrl)
  }
  
  // 从images数组中移除对应的文件
  if (productForm.value.images && index < productForm.value.images.length) {
    productForm.value.images.splice(index, 1)
  }
  
  // 如果图片数量满足要求，清除错误
  if (productForm.value.images && productForm.value.images.length > 0) {
    delete errors.value.images
  }
}

// 取消发布
const handleCancel = () => {
  if (confirm('确定要取消发布吗？已填写的内容将丢失')) {
    router.push('/')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }

  loading.value = true
  try {
    // 构造FormData对象
    const formData = new FormData()
    formData.append('title', productForm.value.title || '')
    formData.append('description', productForm.value.description || '')
    formData.append('price', productForm.value.price || '')
    // 添加图片文件
    if (productForm.value.images) {
      productForm.value.images.forEach((file, index) => {
        formData.append(`images`, file)
      })
    }
    
    // 调用后端API提交商品信息
    await productService.createProduct(formData)
    
    ElMessage.success('商品发布成功！')
    router.push('/')
  } catch (error) {
    console.error('发布商品失败:', error)
    ElMessage.error('发布失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 上传前的检查
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }
  
  return true
}
</script>

<template>
  <div class="product-create-container">
    <el-card>
      <template #header>
        <h1>发布二手商品</h1>
      </template>
      
      <el-form @submit.prevent="handleSubmit" class="product-form" label-width="100px">
        <el-form-item label="商品名称" :error="errors.name" required>
          <el-input 
            v-model="productForm.title" 
            placeholder="请输入商品名称" 
            clearable
          />
        </el-form-item>
        
        <el-form-item label="商品描述" :error="errors.description" required>
          <el-input 
            v-model="productForm.description" 
            placeholder="请详细描述商品状况、使用情况等" 
            type="textarea" 
            :rows="5"
          />
        </el-form-item>
        
        <el-form-item label="价格 (元)" :error="errors.price" required>
          <el-input 
            v-model="productForm.price" 
            placeholder="请输入价格" 
            type="number" 
            :step="0.01" 
            :min="0"
          />
        </el-form-item>
        
        
        <el-form-item label="商品图片" :error="errors.images" required>
          <div class="image-preview-container">
            <!-- 现有图片预览 -->
            <div v-for="(url, index) in imagePreviewUrls" :key="index" class="image-preview">
              <img :src="url" alt="商品图片" />
              <el-button 
                type="danger" 
                size="small" 
                @click="removeImage(index)"
                circle
                style="position: absolute; top: -10px; right: -10px;"
              >
                ×
              </el-button>
            </div>
            
            <!-- 上传新图片按钮 -->
            <div 
              v-if="imagePreviewUrls.length < 5"
              class="upload-button"
              @click="triggerUpload"
            >
              <el-icon><Plus /></el-icon>
              <div style="font-size: 12px; margin-top: 4px;">上传图片</div>
            </div>
            
            <!-- 隐藏的文件输入框 -->
            <input 
              ref="fileInput"
              type="file"
              multiple
              accept="image/*"
              style="display: none;"
              @change="handleFileSelect"
            />
          </div>
          <p style="color: #666; font-size: 0.9em; margin-top: 10px;">
            支持JPG、PNG格式，最多上传5张图片，每张不超过5MB
          </p>
        </el-form-item>
        
        <div class="form-actions">
          <!-- 加载状态 -->
          <div v-if="loading" class="loading-container">
            <LoadingSpinner />
          </div>
          <!-- 正常状态 -->
          <div v-else>
            <el-button type="primary" native-type="submit">发布商品</el-button>
            <el-button @click="handleCancel">取消</el-button>
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.product-create-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.product-create-container h1 {
  text-align: center;
  color: #333;
  margin: 0;
}

.product-form {
  padding: 20px 0;
}

.form-actions {
  display: flex;
  gap: 10px;
  justify-content: center;
  margin-top: 30px;
}

.image-preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-preview {
  position: relative;
  width: 100px;
  height: 100px;
}

.image-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.upload-button {
  width: 100px;
  height: 100px;
  border: 2px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  color: #666;
  transition: border-color 0.3s;
}

.upload-button:hover {
  border-color: #409eff;
  color: #409eff;
}

.no-data {
  text-align: center;
  padding: 40px 20px;
  color: #666;
}
</style>